﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManager : MonoBehaviour {

	public GameObject pinPrefabs;
	private Transform startPoint; 
	private Transform spawnPoint;
	//当前帧
	private Pin currentPin;
	//游戏是否结束
	private bool isGameOver=false;
	//分数
	private int Score = 0;
	private Text scoreText;
	private Camera mainCamera;
	//动画速度
	public float AnimSpeed=3;


	void Start()
    {
		startPoint = GameObject.Find("StartPoint").transform;
		spawnPoint = GameObject.Find("SpawnPoint").transform;
		scoreText = GameObject.FindObjectOfType<Text>();
		mainCamera = Camera.main;

		SpawnPin();
	}
	// Update is called once per frame
	private void Update() 
	{
		if (isGameOver) return;

        //检测按下鼠标左键   发射针
        if (Input.GetMouseButtonDown(0))
        {
			Score++;
			scoreText.text = Score.ToString();
			//开始飞行
			currentPin.StartFly();
			SpawnPin();
		}
	}

	/// <summary>
	/// 生成针
	/// </summary>
	void SpawnPin()
	{
		//实例化当前帧 组件   预制体，位置，旋转角度
		currentPin= GameObject.Instantiate(pinPrefabs,spawnPoint.position,pinPrefabs.transform.rotation).GetComponent<Pin>();
	}
	public void GameOver()
	{
		if (isGameOver) return;
		GameObject.Find("Circle").GetComponent<RotateSeft>().enabled=false;
		
		Score -= 1;
		scoreText.text = Score.ToString();

		StartCoroutine(GameOverAnim());
		isGameOver = true;
	}
	/// <summary>
	/// 结束动画
	/// </summary>
	/// <returns></returns>
	IEnumerator GameOverAnim()
	{
        while (true)
        {
			//lerp朝向目标值
			//颜色
			mainCamera.backgroundColor = Color.Lerp(mainCamera.backgroundColor,Color.red,AnimSpeed * Time.deltaTime);
			//大小  5到4
			mainCamera.orthographicSize = Mathf.Lerp(mainCamera.orthographicSize,4,AnimSpeed * Time.deltaTime);
            
			if (Mathf.Abs(mainCamera.orthographicSize-4)<0.01f)
				//判断绝对值 是否到达目标值  -结束循环
            {
				break;
            }
			yield return 0;
        }
		yield return new WaitForSeconds(1);//等待一秒
										   //重新加载场景
		SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
	}
}
